<template>
  <div class="channel_edit">
      <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
          <van-button
          size="mini"
          type="info"
          @click="editing=!editing">
          {{editing ? '取消' : '编辑'}}
          </van-button>
      </van-cell>
      <van-grid>
        <van-grid-item
        :class="{'cur':idx === activeIndex}"
        v-for="(channel, idx) in channels"
        @click="toggleChannel(channel)"
        :key="channel.id">
          <span>{{channel.name}}</span>
          <van-icon v-if="editing && channel.id !== 0" name="cross" class="btn"></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
     <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid>
        <van-grid-item
        v-for="item in recommendChannels"
        :key="item.id"
        @click='addChannels(item)'>
          <span>{{item.name}}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { getAllChannels, addChannel, delChannel } from '@/api/channel'
export default {
  name: 'ChannelEdit',
  props: ['channels', 'activeIndex'],
  data () {
    return {
      allChannels: [],
      editing: false
    }
  },
  computed: {
    recommendChannels () {
      const result = this.allChannels.filter(channel => {
        const idx = this.channels.findIndex(item => item.id === channel.id)
        if (idx === -1) {
          // 没有找到
          return true
        } else {
          return false
        }
      })
      return result
    }
  },
  created () {
    this.loadAllChannles()
  },
  methods: {
    //   添加频道操作
    async addChannels (channel) {
      let currentChannelList = [...this.channels, channel]
      currentChannelList = currentChannelList.map((item, idx) => {
        return {
          id: item.id,
          seq: idx
        }
      })
      // 不要将推荐传入进去
      currentChannelList.splice(0, 1)

      await addChannel(currentChannelList)

      // 更新内容
      this.channels.push(channel)
    },
    // 点击我的频道 主界面切换到这个频道
    async toggleChannel (channel) {
      if (this.editing === true) {
        if (channel.id === 0) {
          return
        }
        await delChannel(channel.id)
        // 更新视图  找到删除的这个元素的下标 删除掉 ok?
        const idx = this.channels.findIndex(item => item.id === channel.id)
        if (idx !== -1) {
          this.channels.splice(idx, 1)
        }
      } else {
        this.$emit('updateCurChannel', channel)
      }
    },
    // 获取全部频道
    async loadAllChannles () {
      const res = await getAllChannels()
      this.allChannels = res.data.data.channels
    }
  }
}
</script>

<style lang='less' scoped>
.cur {
    color:red;
    font-weight: bold;
}
</style>
